package com.face.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.face.common.pojo.DataGridResult;
import com.face.common.pojo.FaceResult;
import com.face.common.utils.MapUtil;
import com.face.mapper.CheckQueryMapper;
import com.face.mapper.TbCheckFaceMapper;
import com.face.mapper.TbCheckMapper;
import com.face.mapper.TbStudentCompanyMapper;
import com.face.mapper.TbStudentMapper;
import com.face.pojo.Query;
import com.face.pojo.QueryResult;
import com.face.pojo.TbCheck;
import com.face.pojo.TbCheckExample;
import com.face.pojo.TbCheckExample.Criteria;
import com.face.pojo.TbCheckFace;
import com.face.pojo.TbCheckFaceExample;
import com.face.pojo.TbStudent;
import com.face.pojo.TbStudentCompany;
import com.face.pojo.TbStudentCompanyExample;
import com.face.service.CheckService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class CheckServiceImpl implements CheckService {

	@Autowired
	private TbCheckMapper checkMapper;

	@Autowired
	private TbStudentMapper studentMapper;
	
	@Autowired
	private TbStudentCompanyMapper companyMapper;
	
	@Autowired
	private CheckQueryMapper checkQueryMapper;
	
	@Autowired
	private TbCheckFaceMapper checkFaceMapper;
	
//	@Override
//	public DataGridResult list(Integer page,Integer rows) {
//		try {
//			TbCheckExample example = new TbCheckExample();
//			Criteria criteria = example.createCriteria();
//			criteria.andIdIsNotNull();
//			PageHelper.startPage(page, rows);
//			List<TbCheck> list = checkMapper.selectByExample(example);
//			List<QueryResult> result = new ArrayList<>();
//
//			for (TbCheck check : list) {
//				QueryResult q = new QueryResult();
//				TbStudent student = studentMapper.selectByPrimaryKey(check.getStudentId());
//				q.setId(check.getId());
//				q.setStudentName(student.getStudentName());
//				q.setCollegeName(student.getCollegeName());
//				q.setMajorName(student.getMajorName());
//				q.setClassName(student.getClassName());
//				q.setCheckType(check.getCheckType());
//				q.setCheckAddress(check.getCheckAddress());
//				q.setCheckTime(check.getCheckTime());
//				q.setCheckYear(check.getCheckYear());
//				result.add(q);
//			}
//			DataGridResult gridResult=new DataGridResult();
//			gridResult.setRows(result);
//			PageInfo<TbCheck> info=new PageInfo<>(list);
//			gridResult.setTotal(info.getTotal());
//			return gridResult;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//		return null;
//	}

	@Override
	public DataGridResult getCheckByCollege(Integer page, Integer rows, String collegeName) {
		try {
			TbCheckExample example = new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andIdIsNotNull();
			PageHelper.startPage(page, rows);
			List<TbCheck> list = checkMapper.selectByExample(example);
			List<QueryResult> result = new ArrayList<>();
			for(TbCheck check:list){
				QueryResult q = new QueryResult();
				TbStudent student = studentMapper.selectByPrimaryKey(check.getStudentId());
				if(student.getCollegeName().equals(collegeName)){
					q.setId(check.getId());
					q.setStudentName(student.getStudentName());
					q.setCollegeName(student.getCollegeName());
					q.setMajorName(student.getMajorName());
					q.setClassName(student.getClassName());
					q.setCheckType(check.getCheckType());
					q.setCheckAddress(check.getCheckAddress());
					q.setCheckTime(check.getCheckTime());
					q.setCheckYear(check.getCheckYear());
					result.add(q);
				}
			}
			DataGridResult gridResult=new DataGridResult();
			gridResult.setRows(result);
			PageInfo<TbCheck> info=new PageInfo<>(list);
			gridResult.setTotal(info.getTotal());
			return gridResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public DataGridResult getCheckByMajor(Integer page, Integer rows, String majorName) {
		try {
			TbCheckExample example = new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andIdIsNotNull();
			PageHelper.startPage(page, rows);
			List<TbCheck> list = checkMapper.selectByExample(example);
			List<QueryResult> result = new ArrayList<>();
			for(TbCheck check:list){
				QueryResult q = new QueryResult();
				TbStudent student = studentMapper.selectByPrimaryKey(check.getStudentId());
				if(student.getMajorName().equals(majorName)){
					q.setId(check.getId());
					q.setStudentName(student.getStudentName());
					q.setCollegeName(student.getCollegeName());
					q.setMajorName(student.getMajorName());
					q.setClassName(student.getClassName());
					q.setCheckType(check.getCheckType());
					q.setCheckAddress(check.getCheckAddress());
					q.setCheckTime(check.getCheckTime());
					q.setCheckYear(check.getCheckYear());
					result.add(q);
				}
			}
			DataGridResult gridResult=new DataGridResult();
			gridResult.setRows(result);
			PageInfo<TbCheck> info=new PageInfo<>(list);
			gridResult.setTotal(info.getTotal());
			return gridResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public DataGridResult getCheckByClass(Integer page, Integer rows, String className,String majorName) {
		try {
			TbCheckExample example = new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andIdIsNotNull();
			PageHelper.startPage(page, rows);
			List<TbCheck> list = checkMapper.selectByExample(example);
			List<QueryResult> result = new ArrayList<>();
			for(TbCheck check:list){
				QueryResult q = new QueryResult();
				TbStudent student = studentMapper.selectByPrimaryKey(check.getStudentId());
				if(student.getMajorName().equals(majorName)&&student.getClassName().equals(className)){
					q.setId(check.getId());
					q.setStudentName(student.getStudentName());
					q.setCollegeName(student.getCollegeName());
					q.setMajorName(student.getMajorName());
					q.setClassName(student.getClassName());
					q.setCheckType(check.getCheckType());
					q.setCheckAddress(check.getCheckAddress());
					q.setCheckTime(check.getCheckTime());
					q.setCheckYear(check.getCheckYear());
					result.add(q);
				}
			}
			DataGridResult gridResult=new DataGridResult();
			gridResult.setRows(result);
			PageInfo<TbCheck> info=new PageInfo<>(list);
			gridResult.setTotal(info.getTotal());
			return gridResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public DataGridResult getCheckByYear(Integer page, Integer rows, String year) {
		try {
			TbCheckExample example = new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andCheckYearEqualTo(Integer.parseInt(year));
			PageHelper.startPage(page, rows);
			List<TbCheck> list = checkMapper.selectByExample(example);
			List<QueryResult> result = new ArrayList<>();
			for(TbCheck check:list){
				QueryResult q = new QueryResult();
				TbStudent student = studentMapper.selectByPrimaryKey(check.getStudentId());
					q.setId(check.getId());
					q.setStudentName(student.getStudentName());
					q.setCollegeName(student.getCollegeName());
					q.setMajorName(student.getMajorName());
					q.setClassName(student.getClassName());
					q.setCheckType(check.getCheckType());
					q.setCheckAddress(check.getCheckAddress());
					q.setCheckTime(check.getCheckTime());
					q.setCheckYear(check.getCheckYear());
					result.add(q);
				
			}
			DataGridResult gridResult=new DataGridResult();
			gridResult.setRows(result);
			PageInfo<TbCheck> info=new PageInfo<>(list);
			gridResult.setTotal(info.getTotal());
			return gridResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public FaceResult getCheckListById(Integer id) {
		TbCheckExample example=new TbCheckExample();
		Criteria criteria = example.createCriteria();
		criteria.andStudentIdEqualTo(id);
		try {
			List<TbCheck> list= checkMapper.selectByExample(example);
			return FaceResult.ok(list);
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500, "服务器发生错误");
		}
		
	}

	@Override
	public FaceResult check(double lng, double lat, Integer id,String checkInfo,String faceAvatar,String facePhone,String faceGroupUid,String faceOpenId) {
		
		boolean b = getCheckInfoByDate(id);
		if(!b){
			return FaceResult.build(500,"每天只能签到两次");
		}
		
		
		TbStudent student = studentMapper.selectByPrimaryKey(id);
		
		TbCheckFaceExample checkFaceExample=new TbCheckFaceExample();
		checkFaceExample.createCriteria().andStudentNumberEqualTo(student.getStudentNumber());
		List<TbCheckFace> list2 = checkFaceMapper.selectByExample(checkFaceExample);
		if(null==list2||list2.size()<0){
			TbCheckFace record=new TbCheckFace();
			record.setId(null);
			record.setCreateTime(new Date());
			record.setUpdateTime(new Date());
			record.setFaceAvatar(faceAvatar);
			record.setFaceGroupUid(faceGroupUid);
			record.setFaceOpenId(faceOpenId);
			record.setFacePhone(facePhone);
			record.setStudentNumber(student.getStudentNumber());
			checkFaceMapper.insert(record);
		}else{
			TbCheckFace face = list2.get(0);
			if(!face.getFaceOpenId().equals(faceOpenId)||!face.getStudentNumber().equals(student.getStudentNumber())){
				return FaceResult.build(500,"签到失败，人脸不匹配");
			}
		}
		
		try {

			TbStudentCompanyExample example=new TbStudentCompanyExample();
			com.face.pojo.TbStudentCompanyExample.Criteria criteria = example.createCriteria();
			criteria.andStudentIdEqualTo(id);
			List<TbStudentCompany> list = companyMapper.selectByExample(example);
			
			if(list!=null&&list.size()>0){
				TbStudentCompany company = list.get(0);
				String string = company.getCompanyAddress();
				if(string==null||string==""){
					return FaceResult.build(500,"请先设置校外实践教学单位");
				}else{
					
					String[] strings = string.split(":");
					double d = MapUtil.Distance(Double.parseDouble(strings[0]), Double.parseDouble(strings[1]),lng, lat);
					TbCheck check=new TbCheck();
					check.setId(null);
					check.setCheckAddress(lng+":"+lat);
					check.setCheckTime(new Date());
					check.setCheckType("已签到");
					check.setCheckYear(new DateTime().getYear());
					check.setStudentId(id);
					check.setCheckInfo(checkInfo);
					if(d<=500.0){
						checkMapper.insert(check);
						return FaceResult.build(200,"签到成功");
					}else{
						return FaceResult.build(500,"签到失败,位置不匹配");
					}
					
				}
			}else{
				return FaceResult.build(500,"请先设置校外实践教学单位");
			}		
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		return FaceResult.build(500,"签到失败，请重试");
		
	}
	
	public boolean getCheckInfoByDate(Integer id){
		
		try {
			TbCheckExample example=new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andStudentIdEqualTo(id);
			List<TbCheck> list = checkMapper.selectByExample(example);
			if(list!=null&&list.size()>0){
				int i=0;
				String start = new DateTime().toString("yyyy-MM-dd");
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
				for(TbCheck tbCheck:list){
					Date date = tbCheck.getCheckTime();
					String old = format.format(date);
					if(old.equals(start)){
						i++;
					}
				}
				if(i>=2){
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	@Override
	public FaceResult insertStudentCompanyInfo(TbStudentCompany company){
		try {
			TbStudentCompanyExample example=new TbStudentCompanyExample();
			example.createCriteria().andStudentIdEqualTo(company.getStudentId());
			List<TbStudentCompany> list = companyMapper.selectByExample(example);
			
			if(null!=list&&list.size()>0){
				company.setId(list.get(0).getId());
				companyMapper.updateByPrimaryKey(company);
			}else{
				companyMapper.insert(company);
			}
			
			return FaceResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return FaceResult.build(500,"设置校外实践失败，请重试！");
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public FaceResult getCheckTypeById(Integer id) {
		try {
			TbCheckExample example=new TbCheckExample();
			Criteria criteria = example.createCriteria();
			criteria.andStudentIdEqualTo(id);
			List<TbCheck> list = checkMapper.selectByExample(example);
			if(list!=null&&list.size()>0){
				TbCheck check = list.get(list.size()-1);
				Date date = check.getCheckTime();
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
				String old = format.format(date);
				String current = new DateTime().toString("yyyy-MM-dd");
				
				if(!current.equals(old)){
					return FaceResult.build(200,"未签到");
				}else{
					int[] pm={12,13,14,15,16,17,18,19,20,21,22,23};
					int oldHours = date.getHours();
					int currentHours = new Date().getHours();
					int i = Arrays.binarySearch(pm,oldHours);
					int j = Arrays.binarySearch(pm,currentHours);
					if(i<=0&&j<=0||i>=0&&j>=0){
						return FaceResult.build(400,"已签到");	
					}else{
						return FaceResult.build(200,"未签到");	
					}
 				}
				
			}else{
				return FaceResult.build(200,"未签到");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return FaceResult.build(200,"未签到");
	}

	@Override
	public DataGridResult list(Integer page, Integer rows,Query query) {
		try {
			PageHelper.startPage(page, rows);
			List<QueryResult> list = checkQueryMapper.query(query);
			DataGridResult result=new DataGridResult();
			result.setRows(list);
			PageInfo<QueryResult> info=new PageInfo<>(list);
			result.setTotal(info.getTotal());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
